accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000;

function check_biz_logic() {
    var currentApplNo = $("#currentApplNo").val();
    if (currentApplNo == "") {
        alert("请查询订单后再管理文件上传！");
        return false;
    }

    var currentUploadDir = $("#currentUploadDir").val();
    if (currentUploadDir == "") {
        alert("请选择文件夹后再管理文件上传！");
        return false;
    }
    return true;
};

function check_file_size(file) {
    var file_size_level0 = 1 * 1024 * 1024;
    var file_size_level1 = 10 * 1024 * 1024;
    var file_size_level2 = 20 * 1024 * 1024;
    if (file.type == "image/jpeg" || file.type == "image/png") {
        if (file.size > file_size_level2) {
            alert("上传图片不能超过20M！");
            return false;
        } else if (file.size > file_size_level1) {
            uploader.settings.resize = {
                width: 1024,
                enabled: true,
                crop: false,
                quality: 60,
                preserve_headers: true
            };
        } else if (file.size > file_size_level0) {
            uploader.settings.resize = {
                width: 1024,
                enabled: true,
                crop: false,
                //quality: 90,
                preserve_headers: true
            };
        }
    }

    return true;
};

function send_request() {
    var currentUploadDir = $("#currentUploadDir").val();
    var retdata;
    $.ajax({
        url: '/oss/getPolicy',
        type: 'GET',
        async: false,
        data: {
            uploaddir: currentUploadDir
        },
        dataType: 'json',
        success: function (data) {
            retdata = data;
        }
    });
    return retdata;
};

function check_object_radio() {
    g_object_name_type = 'local_name';
};

function get_signature() {
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3) {
        var obj = send_request();
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = eval('');
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name') {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if (g_object_name_type == 'random_name') {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret) {
    if (ret == false) {
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        'callback': callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
    up.start();
}
function del_div_byId(id) {
    $(id).remove();
}
var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'selectfiles',
    multi_selection: true,
    container: document.getElementById('oss-upload-container'),
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',
    resize: {},
    filters: {
        mime_types: [ //允许上传图片类型
            {title: "Image files", extensions: "jpg,gif,png,bmp"},
            {title: "Zip files", extensions: "zip,rar"},
            {title: "Movie files", extensions: "mp4"},
            {title: "Pdf files", extensions: "pdf"}
        ],
        max_file_size: '50mb', //最大只能上传50mb的文件
        prevent_duplicates: true //不允许选取重复文件
    },

    init: {
        PostInit: function () {
            document.getElementById('ossfile').innerHTML = '';
            document.getElementById('postfiles').onclick = function () {
                if (check_biz_logic()) {
                    set_upload_param(uploader, '', false);
                }
                return false;
            };
        },

        FilesAdded: function (up, files) {
            plupload.each(files, function (file) {
                document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b><b><a href="javascript:del_div_byId(' + file.id + ');">删除</a></b>'
                    + '<div class="oss-progress"><div class="oss-progress-bar" style="width: 0%"></div></div>'
                    + '</div>';
            });
        },

        BeforeUpload: function (up, file) {
            if (check_biz_logic()) {
                check_object_radio();
                if (!check_file_size(file)) {
                    return false;
                }
                set_upload_param(up, file.name, true);
            } else {
                return false;
            }
        },

        UploadProgress: function (up, file) {

            var d = document.getElementById(file.id);
            if (d != null) {
                d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                var prog = d.getElementsByTagName('div')[0];
                var progBar = prog.getElementsByTagName('div')[0]
                progBar.style.width = 3 * file.percent + 'px';
                progBar.setAttribute('aria-valuenow', file.percent);
            } else {
                uploader.removeFile(file);
            }
        },

        FileUploaded: function (up, file, info) {
            if (info.status == 200) {
                /*document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '文件上传成功, 文件名:' + get_uploaded_object_name(file.name);*/
                $.ajax({
                    url: '/mgr/addMediaRecord',
                    type: 'POST',
                    async: true,
                    data: {
                        currentApplNo: $("#currentApplNo").val(),
                        currentUploadDir: $("#currentUploadDir").val() + file.name
                    },
                    dataType: 'html',
                    success: function (data) {
                    }
                });
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功!';
                document.getElementById(file.id).getElementsByTagName('b')[1].innerHTML = '';
            }
            else {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
            }
        },

        Error: function (up, err) {
            if (err.code == -600) {
                alert("选择的文件太大。");
            }
            else if (err.code == -601) {
                alert("请选择正确的文件类型。");
            }
            else if (err.code == -602) {
                alert("请勿重复上传相同的文件。");
            }
            else {
                alert("上传出错，请联系系统管理员。");
            }
        }
    }
});

uploader.init();

